import React from 'react';
import { Avatar, Spin } from 'antd';
import type { MenuProps } from 'antd';
import { ItemType, MenuDividerType } from 'antd/lib/menu/hooks/useItems';
import { history, ConnectProps, connect } from 'umi';
import { LogoutOutlined, SettingOutlined, UserOutlined } from '@ant-design/icons';
import { ConnectState } from '@/models/connect';
import { CurrentUser } from '@/models/user';
import HeaderDropdown from '../HeaderDropdown';
import styles from './index.less';

export interface GlobalHeaderRightProps extends Partial<ConnectProps> {
  currentUser?: CurrentUser;
  menu?: boolean;
}

class AvatarDropdown extends React.Component<GlobalHeaderRightProps> {

  render(): React.ReactNode {
    const {
      currentUser = {
        avatar: '',
        name: '',
      },
      menu,
    } = this.props;
    const menuItems: ItemType[] = [];
    if (menu) {
      menuItems.push({
        key: 'center',
        icon: <UserOutlined />,
        label: '个人中心',
      });
      menuItems.push({
        key: 'settings',
        icon: <SettingOutlined />,
        label: '个人设置',
      });
      // 菜单项分割线，只用在弹出菜单内
      const dividerItem: MenuDividerType = {
        type: 'divider', // Must have
      };
      menuItems.push(dividerItem);
    }
    menuItems.push({
      key: 'logout',
      icon: <LogoutOutlined />,
      label: '退出登录',
    });
    const onClick: MenuProps['onClick'] = ({ key }) => {
      // console.info(key);
      if (key === 'logout') {
        const { dispatch } = this.props;
        if (dispatch) {
          dispatch({
            type: 'login/logout',
          });
        }
        return;
      }
      history.push(`/account/${key}`);
    };
    return currentUser && currentUser.name ? (
      <HeaderDropdown
        menu={{
          selectedKeys: [],
          onClick: onClick,
          items: menuItems,
        }}
      >
        <span className={`${styles.action} ${styles.account}`}>
          <Avatar size="small" className={styles.avatar} src={currentUser.avatar} alt="avatar" />
          <span className={`${styles.name} anticon`}>{currentUser.name}</span>
        </span>
      </HeaderDropdown>
    ) : (
      <span className={`${styles.action} ${styles.account}`}>
        <Spin
          size="small"
          style={{
            marginLeft: 8,
            marginRight: 8,
          }}
        />
      </span>
    );
  }
}

export default connect(({ user }: ConnectState) => ({
  currentUser: user.currentUser,
}))(AvatarDropdown);
